package routers

import (
	"fmt"
	"goend/controllers"
	"goend/logs"
	"io"
	"net/http"
	"os"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/robfig/cron"
)

var f *os.File

func init() {
	router := gin.New()
	// 添加 Logger 中间件
	router.Use(gin.Logger())

	// 添加 Recovery 中间件
	router.Use(gin.Recovery())
	initRoute(router)
	gin.DisableConsoleColor()
	//ginlog
	nowdate := time.Now()
	year, month, day := nowdate.Date()
	logFileName := fmt.Sprintf("logs/gin%d%d%d.log", year, int(month), day)
	_, err := os.Stat(logFileName)
	if os.IsNotExist(err) {
		f, _ = os.Create(logFileName)
		logs.PrintLog("router.go: " + logFileName + " is not exist create")
	} else {
		f, _ = os.OpenFile(logFileName, os.O_APPEND|os.O_WRONLY, 0644)
		logs.PrintLog("router.go: " + logFileName + " exist create,bind")
	}
	gin.DefaultWriter = io.MultiWriter(f)
	//定时任务
	cron.New().AddFunc("* * 0 * * *", func() {
		nowdate := time.Now()
		year, month, day := nowdate.Date()
		logFileName := fmt.Sprintf("logs/gin%d%d%d.log", year, int(month), day)
		_, err = os.Stat(logFileName)
		if os.IsNotExist(err) {
			f, _ = os.Create(logFileName)
			logs.PrintLog("router.go: " + logFileName + "is not exist create")
		} else {
			f, _ = os.OpenFile(logFileName, os.O_APPEND|os.O_WRONLY, 0644)
			logs.PrintLog("router.go: " + logFileName + "exist create,bind")
		}
		gin.DefaultWriter = io.MultiWriter(f)
	})
	router.Run("0.0.0.0:8090")

}

func cors() gin.HandlerFunc {
	//跨域
	return func(c *gin.Context) {
		c.Header("Access-Control-Allow-Origin", "*")
		c.Header("Access-Control-Allow-Headers", "Content-Type,AccessToken,X-CSRF-Token,Authorization,Token")
		c.Header("Access-Control-Allow-Methods", "POST,GET,OPTIONS")
		c.Header("Access-Control-Expose-Headers", "Content-Length,Access-Control-Allow-Origin,Access-Control-Allow-Headers,Content-Type")
		c.Header("Access-Control-Allow-Credentials", "True")
		if c.Request.Method == "OPTIONS" {
			c.AbortWithStatus(http.StatusNoContent)
		}
		c.Next()
	}
}

func initRoute(router *gin.Engine) {
	//路由组
	router.SetTrustedProxies(nil)
	router.Use(cors())
	v1 := router.Group("/vistor")
	{
		v1.GET("/api1", controllers.Get2)
		v1.GET("/videos/*ts", controllers.GetVedio)
		v1.GET("/videoslist", controllers.GetNewList)
		v1.POST("/videoskinds", controllers.GetVideoByKinds)
		//v1.POST("/login", controllers.UserLogin)
	}
	// v2 := router.Group("/user")
	// {
	// 	//v2.POST("/CreateAccount", controllers.CreateAccount)
	// 	//v2.POST("/LoginAccount", controllers.LoginAccount)
	// }
}
